package com.netease.xone.widget;

import java.io.File;

import media.MediaRecorderWrapper;
import protocol.XoneService;
import protocol.meta.LoopBack;
import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.support.v4.app.FragmentActivity;
import android.util.DisplayMetrics;
import android.view.ContextMenu;
import android.view.ContextMenu.ContextMenuInfo;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.netease.framework.widget.CustomAlertDialog;
import com.netease.pkgRelated.XoneConsts;
import com.netease.xone.R;
import com.netease.xone.activity.ActivityDiscussTip;
import com.netease.xone.activity.ActivityImageProcess;
import com.netease.xone.activity.ActivityUtil;
import com.netease.xone.app.XoneApp;
import com.netease.xone.fragment.FragmentBase;
import com.netease.xone.itemview.ItemViewTipBase;
import com.netease.xone.view.DiscussRecorderView;
import com.netease.xone.widget.DiscussEditWrapper.ViewTag;
import com.netease.xone.widget.ViewPagerChild.onEmoticonClickListener;
import com.netease.xone.widget.ViewPagerChild.onEmoticonTouchListener;

public class DiscussEmoticonWrapper implements OnClickListener {
    public static final String TAG = DiscussEmoticonWrapper.class.getSimpleName();

    // 录音和键盘切换
    private boolean mKeyboardOrAudio = false;
    // 表情和键盘切换
    private boolean mKeyboardOrSmile = false;
    // 最少录音时长为2S
    private int mMinDuration = 2*1000;
    
	private String mId = null;
	private FragmentActivity mActivity = null;
	private FragmentBase mFragment = null;
	private ViewGroup mRootView = null;
	private DisplayMetrics mDm;
	private DiscussRecorderView mImageViewRecorder;
	private MediaRecorderWrapper mRecorder;
	
	public DiscussEmoticonWrapper(FragmentBase fragment, ViewGroup root, String id) {
	    this(fragment.getActivity(), root, id);
	    this.mFragment = fragment;
	}
	
	private DiscussEmoticonWrapper(FragmentActivity activity, ViewGroup root, String id) {
		if (null == activity || null == root) {
			throw new IllegalArgumentException();
		}
		
		this.mId = id;
		this.mActivity = activity;
		this.mRootView = root;
		init();
	}
	
	private void init() {
	    mRootView.findViewById(R.id.recorder_container).setVisibility(View.GONE);
	    mRootView.findViewById(R.id.send_emoticonView).setVisibility(View.GONE);
	    
	    /**
	     * 设置关联内容id
	     */
	    ViewTag tag = null;
	    tag = new ViewTag();
	    tag.id = R.id.recorder_container;
	    mRootView.findViewById(R.id.send_button_audio).setTag(tag);
	    tag = new ViewTag();
        tag.id = R.id.send_emoticonView;
	    mRootView.findViewById(R.id.send_button_smile).setTag(tag);
	    
		/**
		 * 注册表情分类点击响应
		 */
		LinearLayout ll = (LinearLayout)mRootView.findViewById(R.id.send_button_layout);
		for (int index = 0; index < ll.getChildCount(); index++) {
			ll.getChildAt(index).setOnClickListener(this);
		}
		
		/**
		 * 注册录音开始结束响应
		 */
		mImageViewRecorder = (DiscussRecorderView)mRootView.findViewById(R.id.recorder);
		mImageViewRecorder.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                if (null == mRootView) {
                    return;
                }
                
                if (v.isSelected()) {
                    v.setSelected(false);
                    onRecorder(v.isSelected());
                    
                    int duration = (int)mRecorder.getDuration();
                    if (mMinDuration <= duration) {
                        LoopBack value = new LoopBack();
                        value.mType = XoneConsts.RESULT_IMAGE_RECORDER;
                        ViewTag tag = new ViewTag();
                        tag.flag = true;
                        tag.duration = duration;
                        tag.path = mRecorder.getFilePath();
                        value.mData = tag;
                        XoneService.getInstance().doLoopBack(value);
                    } else {
                        mFragment.showToast(R.string.discuss_voice_too_soon);
                    }
                    mRootView.findViewById(R.id.send_button_audio).performClick();
                    
                } else {
                    v.setSelected(true);
                    onRecorder(v.isSelected());
                }
                mFragment.getSherlockActivity().invalidateOptionsMenu();
            }
        });
		/**
		 * 注册录音倒计时
		 */
		mImageViewRecorder.setRemain((TextView)mRootView.findViewById(R.id.recorder_remain));
		setRecorderTip(false);
		
		/**
		 * 注册表情放大镜功能
		 */
		((ViewPagerEmoticon)mRootView.findViewById(R.id.send_emoticonView)).setOnEmoticonTouchListener(mEmoticonTouchListener);
		
		/**
		 * 初始化录音
		 */
		mRecorder = MediaRecorderWrapper.getInstance();
		mRecorder.setFilePath(getFilePathByType(TYPE_RECORDER, mId));
	}

	public OnClickListener getOnButtonClickListener() {
        return this;
    }
	
	public void setOnEmoticonClickListener(onEmoticonClickListener l) {
		((ViewPagerEmoticon)mRootView.findViewById(R.id.send_emoticonView)).setOnEmoticonClickListener(l);
	}
	
	private OnClickListener mButtonOnClickListener = null;
	public void setOnButtonClickListener(OnClickListener l) {
		mButtonOnClickListener = l;
	}
	
	public void clear() {
		mId = null;
		mActivity = null;
		((ViewPagerEmoticon)mRootView.findViewById(R.id.send_emoticonView)).setOnEmoticonTouchListener(null);
		((ViewPagerEmoticon)mRootView.findViewById(R.id.send_emoticonView)).setOnEmoticonClickListener(null);
		mRootView = null;
		mDm = null;
		mEmoticonTouchListener = null;
		mButtonOnClickListener = null;
	}
	
	/** 是否显示表情框 */
	private void mEmoticonGridControl(boolean bShow) {
		View emoticonView = null;
		emoticonView = mRootView.findViewById(R.id.send_emoticonView);
		Animation animation = null;
		if (bShow) {
			if (mDm == null) {
				mDm = new DisplayMetrics();
				mActivity.getWindowManager().getDefaultDisplay().getMetrics(mDm);
			}
			emoticonView.setVisibility(View.VISIBLE);
			animation = AnimationUtils.loadAnimation(mActivity.getApplicationContext(), R.anim.pop_show_bottom_to_top);
		} else {
			emoticonView.setVisibility(View.GONE);
			animation = AnimationUtils.loadAnimation(mActivity.getApplicationContext(), R.anim.pop_hide_top_to_bottom);
		}
		emoticonView.startAnimation(animation);
	}
	
	/**
	 * 选中按钮处理，要使其它的按钮非选中,以及按钮下面区域内容切换
	 * @param v
	 */
	private void setSelected(int id) {
		/**
		 * 按钮切换
		 */
		LinearLayout ll = (LinearLayout)mRootView.findViewById(R.id.send_button_layout);
		for (int index = 0; index < ll.getChildCount(); index++) {
			if (ll.getChildAt(index).getId() != id) {
				ll.getChildAt(index).setSelected(false);
			}
		}
		
        ll = (LinearLayout)mRootView.findViewById(R.id.emote_container);
        int count = ll.getChildCount();
        for (int index = 0; index < count; index++) {
            if (ll.getChildAt(index).getId() != id) {
                ll.getChildAt(index).setVisibility(View.GONE);
            } else {
                if (View.VISIBLE == ll.getChildAt(index).getVisibility()) {
                    ll.getChildAt(index).setVisibility(View.GONE);
                } else {
                    ll.getChildAt(index).setVisibility(View.VISIBLE);
                }
            }
        }
	}

	private void enableButtonsAndEdit(boolean b) {
	    if (null == mRootView) {
	        return;
	    }
	    
	    // 设置按钮是否可点击
	    LinearLayout ll = (LinearLayout)mRootView.findViewById(R.id.send_button_layout);
        for (int index = 0; index < ll.getChildCount(); index++) {
            ll.getChildAt(index).setClickable(b);
        }
        
        // 设置输入框是否可点击
        mRootView.findViewById(R.id.send_edit_postmessage).setEnabled(b);
	}
	
	private void onButtonClick(View v) {
		if (null != mButtonOnClickListener) {
			mButtonOnClickListener.onClick(v);
		}
	}
	
	/**
	 * 控制录音开始结束
	 * @param start true 开始录音， false 结束录音
	 */
	private void onRecorder(boolean start) {
	    if (start) {
	        mRecorder.stop();
	        mRecorder.start();
	        mImageViewRecorder.start();
	        enableButtonsAndEdit(false);
        } else {
            mRecorder.stop();
            mImageViewRecorder.stop();
            enableButtonsAndEdit(true);
        }
	    
	    if (mImageViewRecorder.isSelected() != start) {
	        mImageViewRecorder.setSelected(start);
	    }
	    
	    setRecorderTip(start);
	}
	
	private void setRecorderTip(boolean start) {
	    if (null == mRootView) {
	        return;
	    }
	    
	    TextView v = (TextView)mRootView.findViewById(R.id.recorder_tip);
	    if (start) {
	        v.setText(R.string.discuss_voice_stop);
	    } else {
	        v.setText(R.string.discuss_voice_start);
	    }
	}
	
	@Override
	public void onClick(View v) {
	    Intent intent = null;
		switch (v.getId()) {
		case R.id.send_button_at:
		    intent = new Intent(mActivity, ActivityDiscussTip.class);
            intent.putExtra(XoneConsts.EXTRA_OPERATE, ItemViewTipBase.TYPE_USER);
            mFragment.startActivity(intent);
			break;
		case R.id.send_button_topic:
		    intent = new Intent(mActivity, ActivityDiscussTip.class);
            intent.putExtra(XoneConsts.EXTRA_OPERATE, ItemViewTipBase.TYPE_TOPIC);
            mFragment.startActivity(intent);
			break;
		case R.id.send_button_theme:
		    intent = new Intent(mActivity, ActivityDiscussTip.class);
            intent.putExtra(XoneConsts.EXTRA_OPERATE, ItemViewTipBase.TYPE_SUBJECT);
            mFragment.startActivity(intent);
			break;
		case R.id.send_button_audio:
		    // 判断是否已经录音，如果已经录音则要提示
		    if (View.VISIBLE  == mRootView.findViewById(R.id.discuss_voice).getVisibility()) {
		        CustomAlertDialog.showAlertDialog(mActivity, 0, -1,
	                    R.string.discuss_voice_title, -1, R.string.discuss_voice_renew,
	                    R.string.cancel, new CustomAlertDialog.DialogListener() {

	                        @Override
	                        public void onClick(DialogInterface DialogListn, int which, int key,
	                                View view) {
	                            if (which == DialogInterface.BUTTON_POSITIVE) {
	                                
	                                LoopBack value = new LoopBack();
	                                value.mType = XoneConsts.RESULT_IMAGE_RECORDER;
	                                ViewTag tag = new ViewTag();
	                                tag.flag = false;
	                                tag.duration = (int)mRecorder.getDuration();
	                                tag.path = mRecorder.getFilePath();
	                                value.mData = tag;
	                                XoneService.getInstance().doLoopBack(value);
	                                mRootView.postDelayed(new Runnable() {
                                        
                                        @Override
                                        public void run() {
                                            mRootView.findViewById(R.id.send_button_audio).performClick();
                                        }
                                    }, 100);
	                            }
	                        }
	                    });
		    } else {
		        setSelected(R.id.recorder_container);
	            if (mKeyboardOrAudio) {
	                ((ImageView)mRootView.findViewById(R.id.send_button_audio)).setImageResource(R.drawable.icon_toolbar_audio_selector);
	            } else {
	                ((ImageView)mRootView.findViewById(R.id.send_button_audio)).setImageResource(R.drawable.icon_toolbar_keyboard_audio);
	            }
	            ((ViewTag)v.getTag()).flag = mKeyboardOrAudio;
	            mKeyboardOrAudio = !mKeyboardOrAudio;
	            ((ImageView)mRootView.findViewById(R.id.send_button_smile)).setImageResource(R.drawable.icon_toolbar_smile_selector);
	            mKeyboardOrSmile = false;
		    }
		    break;
		case R.id.send_button_smile:
		    setSelected(R.id.send_emoticonView);
		    if (mKeyboardOrSmile) {
		        ((ImageView)mRootView.findViewById(R.id.send_button_smile)).setImageResource(R.drawable.icon_toolbar_smile_selector);
            } else {
                ((ImageView)mRootView.findViewById(R.id.send_button_smile)).setImageResource(R.drawable.icon_toolbar_keyboard_smile);
                mEmoticonGridControl(true);
            }
		    ((ViewTag)v.getTag()).flag = mKeyboardOrSmile;
		    mKeyboardOrSmile = !mKeyboardOrSmile;
		    ((ImageView)mRootView.findViewById(R.id.send_button_audio)).setImageResource(R.drawable.icon_toolbar_audio_selector);
		    mKeyboardOrAudio = false;
			/**
			 * 停止录音
			 */
			onRecorder(false);
			break;
		case R.id.send_button_photo:
		    /**
		     * 停止录音
		     */
		    onRecorder(false);
		    if (null != mActivity) {
		        mFragment.registerForContextMenu(v);
		        v.setSelected(false);
		        v.performLongClick();
		    }
		    break;
		default:
		    /**
		     * 点击输入区域时的处理
		     */
		    setSelected(0);
            ((ImageView)mRootView.findViewById(R.id.send_button_smile)).setImageResource(R.drawable.icon_toolbar_smile_selector);
            mKeyboardOrSmile = false;
            ((ImageView)mRootView.findViewById(R.id.send_button_audio)).setImageResource(R.drawable.icon_toolbar_audio_selector);
            mKeyboardOrAudio = false;
		    return;
		}
		onButtonClick(v);
	}
	
	private onEmoticonTouchListener mEmoticonTouchListener = new onEmoticonTouchListener() {
		@Override
		public void onClickUp(String phrase) {

		}

		@Override
		public void onClickDown(View view, String phrase, String title) {

		}

	};
	
	private final int PIC_ALBUM = 1;
	private final int PIC_CAMERA = 2;
	
	public static final int TYPE_BASE = 0;
	public static final int TYPE_PREVIEW  = TYPE_BASE;
	public static final int TYPE_CAMERA   = TYPE_BASE + 1;
	public static final int TYPE_RECORDER = TYPE_BASE + 2;
	
	public static String getFilePathByType(int type, String id) {
		String path = null;
		String filePath = null;
		path = XoneApp.getAppInstance().getCacheDir().toString() + File.separator; 
		if (!new File(path).exists()) {
			new File(path).mkdirs();
		}
		
		if (TYPE_PREVIEW == type) {
			filePath = path + "image_preview_"+ id + ".png";
		} else if (TYPE_CAMERA == type) {
			filePath = path + "pic_camera_"+ id + ".png";
		} else if (TYPE_RECORDER == type) {
		    filePath = path + "media_recorder_"+ id + ".3gp";
		}
		
		return filePath;
	}
	
	public static void delCacheFile(String id) {
	    File file = null;
	    String path = null;
	    
	    path = getFilePathByType(TYPE_PREVIEW, id);
	    file = new File(path);
	    if (file.exists()) {
	        file.delete();
	    }
	    
	    path = getFilePathByType(TYPE_CAMERA, id);
        file = new File(path);
        if (file.exists()) {
            file.delete();
        }
        
        path = getFilePathByType(TYPE_RECORDER, id);
        file = new File(path);
        if (file.exists()) {
            file.delete();
        }
	}
	
	public void onCreateContextMenu(ContextMenu menu, View v,
			ContextMenuInfo menuInfo) {
		if (R.id.send_button_photo == v.getId()) {
			menu.setHeaderTitle(mActivity.getString(R.string.discuss_insert_image));
			menu.add(0, PIC_ALBUM, 0, mActivity.getString(R.string.discuss_old_image));
			menu.add(0, PIC_CAMERA, 0, mActivity.getString(R.string.discuss_new_image));
		}
	}

	public boolean onContextItemSelected(MenuItem item) {
		boolean bRes = false;
		
		switch (item.getItemId()) {
		case PIC_ALBUM:
		    ActivityUtil.selectPictureForResult(mFragment, XoneConsts.RESULT_SELECT_PICTURE);
			break;
		case PIC_CAMERA:
		    ActivityUtil.capturePhotoForResult(mFragment, getFilePathByType(TYPE_CAMERA, mId), XoneConsts.RESULT_CAPTURE_PHOTO);
			break;
		default:
			break;
		}
		
		return bRes;
	}
	
	public boolean onActivityResult(int requestCode, int resultCode, Intent data) {
		boolean bRes = true;
		
		do {
			if (resultCode != Activity.RESULT_OK) {
				bRes = false;
				break;
			}
			Intent intent = null;
			
			switch (requestCode) {
			case XoneConsts.RESULT_SELECT_PICTURE:
			    if (null == data) {
			        break;
			    }
				intent = new Intent(mActivity, ActivityImageProcess.class);
				intent.putExtra(XoneConsts.EXTRA_PATH, getFilePathByType(TYPE_PREVIEW, mId));
				intent.putExtra(XoneConsts.EXTRA_OPERATE, false);
				intent.putExtra(XoneConsts.EXTRA_DURATION, 0);
				intent.setData(data.getData());
				mFragment.startActivityForResult(intent, XoneConsts.RESULT_IMAGE_PREVIEW);
				break;
			case XoneConsts.RESULT_CAPTURE_PHOTO:
				intent = new Intent(mActivity, ActivityImageProcess.class);
				intent.putExtra(XoneConsts.EXTRA_PATH, getFilePathByType(TYPE_PREVIEW, mId));
				intent.putExtra(XoneConsts.EXTRA_OPERATE, false);
				intent.putExtra(XoneConsts.EXTRA_DURATION, 0);
				intent.setData(Uri.fromFile(new File(getFilePathByType(TYPE_CAMERA, mId))));
				mFragment.startActivityForResult(intent, XoneConsts.RESULT_IMAGE_PREVIEW);
				break;
			default:
				bRes = false;
			}
		} while(false);
		
		return bRes;
	}
}
